package cn.cyh.imeans.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author DELL
 * @date 2022/8/24
 */
public class AesUtil {
    private AesUtil(){}

    /**
     * AES加密
     * @param source 加密字符串
     * @param key 长度为16位
     * @return 加密后的字符串，base64编码
     * @throws Exception 异常
     */
    public static String encrypt(String source, String key) throws Exception {
        byte[] raw = key.getBytes(StandardCharsets.UTF_8);
        byte[] src = source.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec keySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        return Base64.getEncoder().encodeToString(cipher.doFinal(src));
    }

}
